/**
 * Created with IntelliJ IDEA.
 * User: teddy zhang
 * Date: 2015-04-06
 * Time: 16:49
 */
define(function(require, exports, module) {
    
    var rk = require('rk');
    
    
    
    require('../../topic/topicOperationCtrl');
    require('core/apps/feed/share');
    
    
    $.widget('rk.fileDetail', {
        options: {
            systemId: null,
            systemItemId: null,
            selector: null,
        },
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var $target = opt.selector;
            me._open($target, elem);
        },
        _open: function($target, contentElem) {
            var me = this;
            var elem = me.element
            var opt = me.options;
            me._render($target, contentElem);
        },
        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
        },
        _render: function($target, contentElem) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var systemId = $.isFunction(opt.systemId) ? opt.systemId.call($target) : $target.attr('systemId');
            var systemItemId = $.isFunction(opt.systemItemId) ? opt.systemItemId.call($target) : $target.attr('systemItemId');
            var picTypes = {
                '.jpg': 1,
                '.jpeg': 1,
                '.png': 1,
                '.bmp': 1,
                '.gif': 1
            };
            rk.get('/json/oa_twitter-file/detail.action', {
                systemId: systemId,
                systemItemId: systemItemId
            }, function(data) {
                if (data.status === 0) {
                    data = data.data;
                    var tf = data.file;
                    var arr = tf.filename.split('.');
                    var fileType = '.' + arr[arr.length - 1];
                    tf.isPic = picTypes[fileType] || 0;
                    tf.starViewRate = Math.min(Math.floor(tf.starRate / 5), 10);
                    tf.downloadUrl = '/json/sns_twitter_file/download.action?fileId=' + data.file.id + '&checkCode=' + data.file.tfcode;
                    tf.userName = data.users[tf.userId].name;
                    tf.userIcon = data.users[tf.userId].icon ? data.users[tf.userId].icon : rk.DEFAULT_USER_ICON;
                    tf.createdAt = moment(tf.createdAt).format('MM月DD日 HH:ss')
                    $.each('groupAccesses,userAccesses,groupDownloadAccesses,userDownloadAccesses'.split(','), function(i, key) {
                        var obj = ~key.indexOf('user') ? data.users : data.groups;
                        data[key] = $.map(data[key], function(item) {
                            return obj[item.id];
                        })
                    });
                    $(contentElem).html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_detail.tpl'), data));
                    /** 评论组件 */
                    $('.js-comments').comment({
                        systemId: systemId,
                        systemItemId: systemItemId,
                        previewList: [],
                        allusers: [],
                        listPosition: 'top'
                    });
                    me._bind($(contentElem), data, $target);
                } else if (data.status == 300002) {
                    data = data.data;
                    data.content = rk.i18n('TWITTERFILE_NOT_EXISTS_OR_DELETED');
                    $(contentElem).html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_detail_deleted.tpl'), data));
                } else if (data.status == 300001) {
                    data = data.data;
                    data.content = rk.i18n('TWITTERFILE_NO_PERMISSION_READ');
                    $(contentElem).html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_detail_deleted.tpl'), data));
                }
            });
        },
        _bind: function($contentElem, data, $target) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            /** 文档展示组件 */
            var $flexpaper = elem.find('div[module="flexpaper"]'),
                id = $flexpaper.css('height', 500).uniqueId().attr('id'),
                flashvars = {
                    SwfFile: escape(data.file.swfurl),
                    Scale: 0.3,
                    ZoomTransition: "easeOut",
                    ZoomTime: 0.5,
                    ZoomInterval: 0.1,
                    FitPageOnLoad: true,
                    FitWidthOnLoad: true,
                    PrintEnabled: true,
                    FullScreenAsMaxWindow: false,
                    ProgressiveLoading: true,
                    PrintToolsVisible: true,
                    ViewModeToolsVisible: false,
                    ZoomToolsVisible: true,
                    FullScreenVisible: true,
                    NavToolsVisible: true,
                    CursorToolsVisible: true,
                    SearchToolsVisible: true,
                    localeChain: "zh_CN"
                };
            new FlexPaperViewer(SESSION.resDomain + '/static/swf/flexpager.swf', id, {
                config: flashvars
            });
            //$('#tf_label_content').topicOperationCtrl({type: 'search', systemId: 502, systemItemId: data.file.id});
            /** 评级事件 */
            $contentElem.on('click', 'ul.star-rating a', function(event) {
                var $this = $(this);
                var $li = $this.parent();
                if (!$li.siblings('li.current-rating').hasClass('current-rating0')) return;
                var param = {
                    fileId: data.file.id,
                    starRate: Number($this.attr('data-value'))
                };
                rk.get('/json/oa_twitter-file/star.action', param, function(reData) {
                    if (reData.status == 0) {
                        var starClassNO = Number($this.attr('title')) * 2;
                        $li.siblings('li.current-rating').removeClass('current-rating0').addClass('current-rating' + starClassNO);
                        $li.siblings('li.current-rating').nextAll().remove();
                    }
                });
                return false;
            });
            /** 下载事件 */
            $contentElem.on('click', 'li.set_download a', function(event) {
                event.preventDefault();
                window.location.href = event.target.href;
                return false;
            });
            /** 收藏事件 */
            $contentElem.on('click', 'li.set_collect a', function(event) {
                event.target.nodeName == 'A' && event.preventDefault();
                var $this = $(this);
                var $li = $this.parent();
                var _style = $li.hasClass('has_collect') ? '' : 'has_collect';
                var favor = (_style == '');
                var fid = data.file.id;
                if (favor) {
                    rk.confirm(rk.i18n('TWITTERFILE_CANCEL_FAVORITES_CONFIRM'), function() {
                        $.postJson('/json/sns_twitter_file_fav/cancel.action', {
                            sid: fid
                        }).done(function(json) {
                            if (json.status == 0) {
                                rk.noticeSuccess(rk.i18n('TWITTERFILE_CANCEL_FAVORITES_SUCCESSFUL'));
                                $li.removeClass('has_collect').addClass(_style);
                            } else {
                                rk.noticeError(rk.i18n('TWITTERFILE_CANCEL_FAVORITES_FAILURE'));
                            }
                        }).fail(function(def, code, message) {
                            def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
                        });
                    });
                } else {
                    $.postJson('/json/sns_twitter_file_fav/save.action', {
                        sid: fid
                    }).done(function(json) {
                        if (json.status == 0) {
                            rk.noticeSuccess(rk.i18n('TWITTERFILE_ADD_FAVORITES_SUCCESSFUL'))
                            $li.removeClass('has_collect').addClass(_style);
                        } else {
                            rk.noticeError(rk.i18n('TWITTERFILE_ADD_FAVORITES_FAILURE'));
                        }
                    }).fail(function(def, code, message) {
                        def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
                    });
                }
                return false;
            });
            /** 分享事件 */
            $contentElem.share({
                selector: 'li.set_share a'
            });
            $("#tf_label_content").topicOperationCtrl({
                type: "search",
                systemId: 502,
                systemItemId: data.file.id,
                successButton: $contentElem.find("[act='tf_label_save']"),
                updateButton: $contentElem.find("[act='tf_label_edit']")
            });
            /** 文档描述编辑事件 */
            $contentElem.on('click', 'a[act="tf_desc_edit"]', function(event) {
                event.target.nodeName == 'A' && event.preventDefault();
                var $this = $(this);
                $this.hide();
                $('a[act="tf_desc_save"]').show();
                var $textarea_HTML = $('<textarea></textarea>').val(!$('#tf_desc_content').find('span').size() ? $.trim($('#tf_desc_content').text()) : '');
                $('#tf_desc_content').empty().append($textarea_HTML);
            });
            /** 文档描述保存事件 */
            $contentElem.on('click', 'a[act="tf_desc_save"]', function(event) {
                event.target.nodeName == 'A' && event.preventDefault();
                var empty_HTML = '<span title="'+rk.i18n('TWITTERFILE_NO_DESCRIPTION')+'" class="editor_pen">'+rk.i18n('TWITTERFILE_NO_DESCRIPTION')+'</span>';
                var $this = $(this);
                var descText = $.trim($('#tf_desc_content').find('textarea').val())
                $.postJson('/json/oa_twitter-file/update-description.action', {
                    fileId: data.file.id,
                    fileDescription: descText,
                }).done(function(json) {
                    $this.hide();
                    $('a[act="tf_desc_edit"]').show();
                    rk.noticeSuccess(rk.i18n('TWITTERFILE_UPDATE_DESCRIPTION_SUCCESSFUL'))
                    if (descText == '') {
                        $('#tf_desc_content').empty().append(empty_HTML);
                    } else {
                        $('#tf_desc_content').empty().append(descText);
                    }
                });
            });
            /** 文档阅读权限事件 */
            $contentElem.on('click', 'a[act="tf_read_permission_edit"]', function(event) {
                event.target.nodeName == 'A' && event.preventDefault();
                var $this = $(this);
                var systemItemId = data.file.id;
                $.postJson('/json/oa_twitter-file/popup-access.action', {
                    systemItemId: systemItemId,
                }).done(function(json) {
                    var data = json.data;
                    $.each('groupAccesses,userAccesses'.split(','), function(i, key) {
                        var obj = ~key.indexOf('user') ? data.users : data.groups;
                        data[key] = $.map(data[key], function(item) {
                            return $.extend({}, {
                                accessId: item.accessId
                            }, obj[item.id]);
                        })
                    });
                    rk.dialog({
                        title: rk.i18n('TWITTERFILE_READ_PERMISSION_SETTING'),
                        width: 630,
                        success: function(contentElem, footElem) {
                            contentElem.html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_read_permission_set.tpl'), data));
                            contentElem.find("#docselect").selectmenu();
                            footElem.on('click', 'a[act="save"]', function(event) {
                                rk.closeDialog();
                                $($target).trigger('click');
                            });
                            //$( ".selector" ).on( "selectmenuchange", function( event, ui ) {} )
                            contentElem.on('selectmenuchange', '#docselect', function(event, ui) {
                                var permission = Number($(this).children('option:selected').val());
                                if (permission) {
                                    contentElem.find('div.no-access-area').show();
                                } else {
                                    contentElem.find('div.no-access-area').hide();
                                }
                            });
                            contentElem.on('click', 'a.delete', function(event) {
                                event.preventDefault();
                                var $this = $(this);
                                rk.confirm(rk.i18n('TWITTERFILE_DELETED_CONFIRM'), function() {
                                    $.postJson('/json/oa_twitter-file/delete-access.action', {
                                        taId: $this.attr('data-value'),
                                    }).done(function(json) {
                                        if (json.status == 0) {
                                            $this.parent().remove();
                                        } else {
                                            rk.noticeError(rk.i18n('TWITTERFILE_SYSTEM_ERROR'));
                                        }
                                    }).fail(function(def, code, message) {
                                        def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
                                    });
                                });
                                return false;
                            });
                            contentElem.on('click', 'a.pg-btn-dustyblue', function(event) {
                                var permission = $("span.ui-select-buttonset").find("option:selected").val();
                                $.postJson('/json/oa_twitter-file/set-access.action', {
                                    systemItemId: systemItemId,
                                    permission: permission,
                                }).done(function(json) {
                                    rk.noticeSuccess(rk.i18n('TWITTERFILE_SET_SUCCESSFUL'));
                                    if (permission) {
                                        if (contentElem.find('div.no-access-area').size() > 0) contentElem.find('div.no-access-area').clear();
                                    }
                                    $($target).trigger('click');
                                });
                            });
                        },
                        footer: ['save'] //弹框的按钮
                    });
                });
                return false;
            });
            /** 文档下载权限事件 */
            $contentElem.on('click', 'a[act="tf_download_permission_edit"]', function(event) {
                event.target.nodeName == 'A' && event.preventDefault();
                var systemItemId = data.file.id;
                var $this = $(this);
                var download = {};
                download.perm = [{
                    tag: 'public',
                    name: rk.i18n('TWITTERFILE_PERMISSION_ALL'),
                    value: -1
                }, {
                    tag: 'specify',
                    name: rk.i18n('TWITTERFILE_PERMISSION_SOME'),
                    value: 3
                }, {
                    tag: 'member',
                    name: rk.i18n('TWITTERFILE_PERMISSION_GROUP'),
                    value: 1
                }, {
                    tag: 'self',
                    name: rk.i18n('TWITTERFILE_PERMISSION_SELF'),
                    value: 2
                }];
                $.postJson('/json/oa_twitter-file/popup-download-access.action', {
                    systemItemId: systemItemId
                }).done(function(json) {
                    var data = json.data;
                    data.perm = download.perm;
                    rk.dialog({
                        title: rk.i18n('TWITTERFILE_DOWNLOAD_PERMISSION_SETTING'),
                        width: 630,
                        success: function(contentElem, footElem) {
                            contentElem.html(rk.templateText(require('oa/tmpl/rescenter/tpl_rescenter_download_permission_set.tpl'), data));
                            var $select = contentElem.find('input.nameselect');
                            contentElem.find("div.ui-radio-buttonset").buttonset();
                            $select.snsmultipeopleselector();
                            $select.snsmultipeopleselector('val', data.users);
                            contentElem.on('change', 'div.ui-radio-buttonset input', function(event) {
                                var $item = $(this);
                                if ($item.attr('data-value') === '3') {
                                    $item.parent().parent().next().show();
                                } else {
                                    $item.parent().parent().next().hide();
                                }
                            });
                            footElem.on('click', 'a[act="save"]', function(event) {
                                var perm = contentElem.find("input[name= 'permission_download']:checked").attr('data-value');
                                var downloadIds = $select.snsmultipeopleselector('val').join(",");
                                if (downloadIds.length < 1 && perm === 3) {
                                    rk.noticeError(rk.i18n('TWITTERFILE_DOWNLOAD_USERS_NOT_SELECTED'));
                                    return;
                                }
                                $.postJson('/json/oa_twitter-file/save-download-access.action', {
                                    systemItemId: systemItemId,
                                    permission: perm,
                                    downloadUserIds: downloadIds
                                }).done(function(json) {
                                    rk.noticeSuccess(rk.i18n('TWITTERFILE_SET_SUCCESSFUL'));
                                    rk.closeDialog();
                                    $($target).trigger('click');
                                });
                            });
                        },
                        footer: ['save'] //弹框的按钮
                    });
                });
                return false;
            });
        }
    });
    return {
        init: function(rkContent, id) {
            rkContent.fileDetail({
                systemId: function() {
                    return 502
                },
                systemItemId: function() {
                    return id
                }
            });
        }
    }
});
